package com.imstlife.vending.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.igexin.sdk.PushManager;
import com.imstlife.vending.R;
import com.imstlife.vending.api.MarvAPI;
import com.imstlife.vending.push.Constants;
import com.imstlife.vending.push.LogUtil;
import com.imstlife.vending.push.NotificationReceiver;
import com.imstlife.vending.push2.push.GTService;
import com.imstlife.vending.push2.push.GeTuiService;
import com.imstlife.vending.utils.AppUtil;
import com.imstlife.vending.utils.Cof;
import com.imstlife.vending.utils.DeviceUtil;
import com.imstlife.vending.utils.RootShellCmd;
import com.imstlife.vending.utils.SharePersistentUtil;
import com.imstlife.vending.utils.T;
import com.imstlife.vending.vo.DeviceLoginResponse;
import com.imstlife.vending.vo.DrinkListVo;
import com.imstlife.vending.vo.GetDrinkListResponse;

import java.util.Timer;
import java.util.TimerTask;

import settings.SettingsActivity;

public class SplashActivity extends Activity implements View.OnClickListener{

    private static  final String TAG = "SplashActivity";
    /**
     * 接收推送广播
     */
    private MainAcNotificationReceiver receiver;

    /**
     * 商品列表
     */
    private DrinkListVo drinkListVo;

    /**
     * 请求失败后  N  秒重试
     */
    private int reGetTime = 5000;

    private TextView tvState;
    private TextView tvSet;

    private String deviceId = "";

    private String deviceModel =  null;//机型

    private String notifyUrl = null;

    private String syncUrl = null;

    /**
     * 推送链接状态
     */
    private boolean connected = false;

    private Timer checkTimer;

    private TimerTask timerTask;

    private ImageView ivCenter;

    private TextView tvDeviceId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RootShellCmd.closeBar();
        setContentView(R.layout.activity_splash);

        PushManager.getInstance().initialize(this.getApplicationContext(), GeTuiService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), GTService.class);
        Debug.startMethodTracing();
        initView();
        initReceiver();

        deviceId = DeviceUtil.getDeviceId(SplashActivity.this);
        T.showLong(SplashActivity.this,"设备号："+deviceId);
        tvDeviceId.setText("设备号："+deviceId);
        Debug.stopMethodTracing();

    }
    private void startCheck(){
        checkTimer = new Timer();
        checkTimer.schedule(timerTask=new TimerTask() {
            @Override
            public void run() {//定时检测获取状态
               Message msg = Message.obtain();
                msg.what = Cof.What.CHECK_LOGIN;
                mHandler.sendMessage(msg);
            }
        },1000,reGetTime);
    }

    private void endCheck(){
        if(checkTimer!=null){
            checkTimer.cancel();
            checkTimer=null;
        }
        if(timerTask!=null){
            timerTask.cancel();
            timerTask=null;
        }

    }

    /**
     * 动态注册广播
     */
    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.ACTION_SHOW_NOTIFICATION);
        filter.addAction("connect");
        filter.addAction("disconnect");
        receiver = new MainAcNotificationReceiver();
        registerReceiver(receiver, filter);
    }

    /**
     * 加载视图控件
     */
    private void initView() {
        tvState = (TextView) findViewById(R.id.tv_ac_splash_state);
        tvSet = (TextView) findViewById(R.id.tv_ac_splash_set);
        tvSet.setOnClickListener(this);
        tvDeviceId = (TextView) findViewById(R.id.tv_ac_main_device_id);
        ivCenter = (ImageView) findViewById(R.id.iv);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_ac_splash_set:
                Intent intent = new Intent(SplashActivity.this, SettingsActivity.class);
                startActivity(intent);
                overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                break;
            default:
                break;
        }
    }

    /**
     * 监听推送连接状态
     */
    public class MainAcNotificationReceiver extends BroadcastReceiver {
        private final String LOGTAG = LogUtil
                .makeLogTag(NotificationReceiver.class);

        public MainAcNotificationReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Message msg = Message.obtain();
            Log.i(TAG,"推送服务："+action);
            if ("connect".equals(action)) {
                msg.what = Cof.What.PUSH_CONECTED;
            } else if ("disconnect".equals(action)) {
                msg.what = Cof.What.PUSH_DISCONNECTED;
            }
            mHandler.sendMessage(msg);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Cof.What.CHECK_LOGIN:
//                    if(connected){
                        checkLoginState();
//                    }
                    break;
                case Cof.What.PUSH_CONECTED:
                    connected = true;
                    break;
                case Cof.What.PUSH_DISCONNECTED:
                    connected = false;
                    break;
                case Cof.What.TOAST:
                    T.showShort(SplashActivity.this,msg.obj.toString());
                    break;
                case Cof.What.NO_NET:
                    noNet(msg.obj.toString());
                    break;
                case Cof.What.OK_NET:
                    tvState.setText(getResources().getString(R.string.get_drink_list));
                    tvSet.setVisibility(View.GONE);
                    break;
            }
        }
    };

    private void checkLoginState(){
        if(drinkListVo==null||drinkListVo.getDrinkList()==null||drinkListVo.getDrinkList().size()<=0||deviceModel==null||notifyUrl==null||syncUrl==null){//

            deviceLogin();
        }else {
            toDrinkListActivity();
        }
    }


    /**
     * 网络未链接，刷新左下角提示
     * @param msg
     */
    private void noNet(String msg){
        tvState.setText(msg);
        tvSet.setVisibility(View.VISIBLE);
    }

    private void sleep(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    private void toDrinkListActivity(){
        Intent intent = new Intent(SplashActivity.this, DrinksActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("drinks", drinkListVo);
        bundle.putString("deviceModel",deviceModel);
        bundle.putString("syncUrl",syncUrl);
        bundle.putString("notifyUrl",notifyUrl);
        intent.putExtras(bundle);
        startActivity(intent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        SplashActivity.this.finish();
    }


    private void notifyUI(String msg){
        tvState.setText("设备号: "+deviceId+" "+msg);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startCheck();
    }

    @Override
    protected void onPause() {
        super.onPause();
        endCheck();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
    public String getDeviceSize() {
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        Log.e("whwh", screenWidth + "    " + screenHeight);
        if (screenWidth == 768) {
            return "8寸";
        } else if (screenWidth == 800) {
            return "10寸";
        } else if (screenWidth == 1024 && screenHeight == 732) {
            return "8寸";
        } else {
            return "7寸";
        }
    }
    private void deviceLogin(){
        notifyUI("正在登陆...");
        MarvAPI.getInstance().deviceLogin(Cof.Interface.URL_DEVICE_LOGIN,  getDeviceSize(),deviceId, AppUtil.getVersionName(this),AppUtil.getVersionCode(this), new MarvAPI.APIListener() {
            @Override
            public void onSuccess(Object data) {
                DeviceLoginResponse response = (DeviceLoginResponse) data;
                if(response!=null){
                    if(response.getStatus()==0){
                        deviceModel = response.getData().getDevModel();
                        syncUrl = response.getData().getSyncUrl();
                        getDrinkList(response.getData().getDrinklistInterfaceAdr());
                        notifyUI("登陆成功，加载商品列表");
                    }else {
                        notifyUI(response.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                notifyUI(msg);
            }

            @Override
            public void onNetError(String msg) {
                noNet(msg);

            }
        });
    }


    private void getDrinkList(String url){

        Log.i(TAG,"deviceId:"+deviceId);
        MarvAPI.getInstance().getDrinkList(url, deviceId, new MarvAPI.APIListener() {
            @Override
            public void onSuccess(Object data) {
                SharePersistentUtil.saveSharePersistent(SplashActivity.this,"tradedata",String.valueOf(data));
                GetDrinkListResponse response = (GetDrinkListResponse) data;
                if (response.getStatus() == 0) {
                    T.showLong(SplashActivity.this,response.getMsg());
                    notifyUrl = response.getNotifyUrl();
                    drinkListVo = new DrinkListVo();
                    drinkListVo.setDrinkList(response.getData());
//                    notifyUrl = response.getNotifyUrl();

                }else {
                    SharePersistentUtil.saveSharePersistent(SplashActivity.this,"tradedata","");
                    notifyUI(response.getMsg());
                }
            }

            @Override
            public void onFailure(String msg) {
                notifyUI(msg);
                SharePersistentUtil.saveSharePersistent(SplashActivity.this,"tradedata","");
            }

            @Override
            public void onNetError(String msg) {
                noNet(msg);
                SharePersistentUtil.saveSharePersistent(SplashActivity.this,"tradedata","");
            }
        });

    }
}
